<?php
include 'int.php';
if ($stmt = $mysqlpdo->prepare("UPDATE system_flag SET flag=0 WHERE name='game_start'")){
	$stmt->execute();
}
while(true){
	if ($stmt = $mysqlpdo->prepare("SELECT flag FROM system_flag WHERE name='game_start'")){
		$stmt->execute();
		$result = $stmt->fetch(PDO::FETCH_BOTH);
		if ($result[0]==1){
			break;
		}
	}else{
		echo "error1\n\r";
	}
	if ($stmt2 = $mysqlpdo->prepare("UPDATE join_game g SET g.joined=0, g.user='', g.session='', g.photo=0 WHERE TIMESTAMPDIFF(SECOND, timeout, NOW())>20")){
		$stmt2->execute();
	}else{
		echo "error2\n\r";
	}
	if ($stmt3 = $mysqlpdo->prepare("SELECT g.u_num FROM join_game g WHERE g.joined=2 OR 9=(SELECT COUNT(*) FROM join_game g WHERE g.joined=0)")){
		$stmt3->execute();
		if ($stmt3->fetch()==null){
			if ($stmt4 = $mysqlpdo->prepare("SELECT g.u_num FROM join_game g WHERE g.u_num = (SELECT MIN(u_num) FROM join_game g2 WHERE g2.joined=1)")){
				$stmt4->execute();
				$result1 = $stmt4->fetch(PDO::FETCH_BOTH);
			}else{
				echo "error3\n\r";
			}
			if ($stmt5 = $mysqlpdo->prepare("UPDATE join_game g SET g.joined=2 WHERE g.u_num=?")){
				$stmt5->bindParam(1, $result1[0], PDO::PARAM_INT);
				$stmt5->execute();
				echo "Defined a new room owner\n\r";
			}else{
				echo "error4\n\r";
			}
		}
	}else{
		echo "error0\n\r";
	}
	sleep(3);
}
?>